#encoding: utf-8

from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import create_app
from exts import db
from apps.cms import models as cms_models

CMSUser = cms_models.CMSUser
CMSRole = cms_models.CMSRole
CMSPermission = cms_models.CMSPermission

app = create_app()

manager = Manager(app)

Migrate(app, db)
manager.add_command('db', MigrateCommand)

@manager.option('-u', '--username', dest='username')
@manager.option('-p', '--password', dest='password')
@manager.option('-e', '--email', dest='email')
@manager.option('-m', '--mobile', dest='mobile')
def create_cms_user(username, password, email, mobile):
    user = CMSUser(username=username, password=password, email=email, mobile=mobile)
    db.session.add(user)
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        raise e
    print('cms用户添加成功')

@manager.command
def create_role():
    # 1.访客(可以修改用户信息)
    visitor = CMSRole(name='访客', desc='只能查看和修改个人信息，没有其他的操作权限')
    visitor.permissions = CMSPermission.VISITOR

    # 2.运营角色(修改个人信息，管理帖子，管理评论，管理前台用户)
    operator = CMSRole(name='运营', desc='查看和修改个人信息，管理帖子，管理评论，管理前台用户')
    operator.permissions = CMSPermission.VISITOR | CMSPermission.POSTER | CMSPermission.FRONTUSER | CMSPermission.COMMENTER

    # 3.管理员角色(拥有大部分权限)
    admin = CMSRole(name='管理员', desc='拥有全部权限')
    admin.permissions = CMSPermission.VISITOR | CMSPermission.POSTER | CMSPermission.FRONTUSER | CMSPermission.COMMENTER \
                        | CMSPermission.CMSUSER | CMSPermission.BOARDER

    # 开发者角色
    developer = CMSRole(name='开发者', desc='开发者专用角色')
    developer.permissions = CMSPermission.ALL_PERMISSION

    db.session.add_all([visitor, operator, admin, developer])
    db.session.commit()

# 添加用户到角色
@manager.option('-e', '--email', dest='email')
@manager.option('-n', '--name', dest='name')
def add_user_to_role(email, name):
    user = CMSUser.query.filter_by(email=email).first()
    if user:
        role = CMSRole.query.filter_by(name=name).first()
        if role:
            role.users.append(user)
            try:
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                raise e
            print('用户添加到角色成功！')
        else:
            print('没有这个角色:%s' %role)
    else:
        print('%s邮箱没有这个用户!' %email)

if __name__ == '__main__':
    manager.run()
